/**
 * Copyright © 2004-2018 ***.All Rights Reserved.
 */
package com.framework.common.jdbc.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * 
 * @version V1.0
 * @author zhoubb
 * @Date 2018-12-04
 * @since JDK 1.7
 */
@Intercepts({ @Signature(type = Executor.class, method = "query", args = {
		MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class OraclePagingInterceptor extends PagingInterceptor {

	@Override
	protected String getPagingSQL(PageParaBean page, String originalSql) {
		int offset = (page.getPage() - 1) * page.getRows();
		offset = offset < 0 ? 0 : offset;
		int end = page.getPage() * page.getRows();
		return String.format("SELECT PAGING_ALIAS_B.* FROM (SELECT PAGING_ALIAS_A.*, ROWNUM AS rn FROM (%s) PAGING_ALIAS_A  WHERE ROWNUM <= %s) PAGING_ALIAS_B WHERE PAGING_ALIAS_B.rn > %s", originalSql, end, offset);
	}
}
